package org.example.springmessage.config;

import org.example.springmessage.mapper.UserMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;



@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.formLogin(form->{
            form.usernameParameter("username")
                    .loginPage("/login.html")
                    .passwordParameter("password")
                    .loginProcessingUrl("/user/login")
                    .successHandler(new MyAcessSuccessHandler());

        });

        //需要认证的资源
        http.authorizeHttpRequests(resp->{
            resp.requestMatchers("/login.html","/register.html").permitAll();  //不需要认证
            resp.requestMatchers("/user/register","/user/login").permitAll();  //不需要认证
            resp.requestMatchers("/css/*.css","/js/*.js","/images/**").permitAll(); //不需要认证
            resp.anyRequest().authenticated();  //其余请求都需要认证
        });

        http.logout(logout->{
            logout.logoutUrl("/user/logout")
                    .clearAuthentication(true)
                    .invalidateHttpSession(true);
        });

        http.cors();

        http.csrf().disable();


        return http.build();

    }

    //不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
}
